package com.sciai.controller;

import cn.com.sciai.aix.common.http.SciaiHttpResponseEntity;
import cn.com.sciai.aix.common.http.SciaiHttpResponseEntityBuilder;
import cn.hutool.core.date.DateUtil;
import com.sciai.entity.CsvData;
import com.sciai.entity.FilePath;
import com.sciai.entity.Weather;
import com.sciai.entity.WeatherType;
import com.sciai.entity.req.TongjieQueryReq;
import com.sciai.mapper.WeatherMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.ibatis.mapping.ResultMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * TODO lb <类名>
 *
 */
@Slf4j
@RestController
@RequestMapping("/exporter")
public class CSVExporter {
    @Resource
    private WeatherMapper weatherMapper;
    @Value("${file.imagPath}")
    private String imagPath;
    @Value("${file.downloadImag}")
    private String downloadImag;
    @Value("${file.downloadVide}")
    private String downloadVide;
    @Value("${file.videoPath}")
    private String videoPath;

    @PostMapping("/exportToCSV")
    public SciaiHttpResponseEntity getExportToCSV(@Validated @RequestBody TongjieQueryReq req) {
        try {

            //查询天气类型
            Map<String, Object> params2 = new HashMap<>();
            List<WeatherType> weatherTypes = weatherMapper.queryWeatherType(params2);
            if (weatherTypes.size()==0){
                return SciaiHttpResponseEntityBuilder.builder().error("500", "没有天气类型的基础数据！").build();
            }
            String fileName ="";
            String name ="";
            int a = Integer.parseInt(req.getWeatherTypeId());
            for (WeatherType weatherType : weatherTypes){
                if (weatherType.getId()==a){
                    if(req.getType().equals("2")){
                        fileName=weatherType.getTypeCode()+"_search";
                    }else {
                        fileName=weatherType.getTypeCode()+"_report";
                    }
                    name=weatherType.getTypeName();
                }
            }

            String starStr = req.getStarTime().toString()+" 00:00:00";
            Date date1 = DateUtil.parse(starStr, "yyyy-MM-dd HH:mm:ss");
            Calendar calendar =new GregorianCalendar();
            calendar.setTime(date1);
            //往后推一天查询当前选择的当天的数据导出
            calendar.add(Calendar.DATE,1);
            Date date2=calendar.getTime();
            String data3 =DateUtil.format(date2,"yyyy-MM-dd HH:mm:ss");
            Date date4 = DateUtil.parse(data3, "yyyy-MM-dd HH:mm:ss");
            List<CsvData> list =new ArrayList<>();
            List<Weather> list2 =new ArrayList<>();
            if(req.getType().equals("2")){
                //导出csv的数据
                Map<String, Object> params = new HashMap<>();
                params.put("date1",date1);
                params.put("date2",date4);
                params.put("WeatherTypeId",a);
                list = weatherMapper.findAllByParams(params);
                log.info("开始file");
                File bcpFile = new File("/opt/project/file/export/"+req.getStarTime()+"/"+fileName+".csv"); //生成文件地址路径--相对路径
                log.info("endfile");
                File parentFile = bcpFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                bcpFile.createNewFile();
//            File bcpFile = new File("D:\\AI+X project\\we-chat\\"+fileName+".csv"); //生成文件地址路径
                byte[] bom ={(byte) 0xEF,(byte) 0xBB,(byte) 0xBF};
                FileOutputStream bcpFileWriter = new FileOutputStream(bcpFile);
                System.out.println("创建文件开始CSV");
                try {
                    bcpFileWriter.write(bom);
                    // 写入文件头部
                    String title = "\"页码\",\"微博id\",\"微博作者\"," +
                            "\"发布时间\",\"微博内容\",\"转发数\",\"评论数\",\"点赞数\",\"发布于\",\"ip属地_城市\",\"ip属地_省份\", " +
                            "\"ip属地_国家\",\"经度\",\"纬度\",\"天气类型\",\"审核结果\"";
                    bcpFileWriter.write((new String(title.getBytes(), "utf-8")).getBytes());
                    bcpFileWriter.write("\n".getBytes());
                    String str = "";
                    if(list!=null && list.size()>0){
                        String param = "";
                        for (int i = 0; i < list.size(); i++) {
                            CsvData csvData = list.get(i);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            String time = simpleDateFormat.format(csvData.getOccurrenceTime());
                            String CHECK = csvData.getCheckIs()==1? "正确":"错误";
                            param = "\"\t"+String.valueOf(csvData.getPageNum())+"\","
                                    +"\"\t"+csvData.getWbId()+"\t\","
                                    +"\"\t"+csvData.getWbName()+"\t\","
                                    +"\"\t"+time+"\t\","
                                    +"\"\t"+csvData.getContent()+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(csvData.getForwardNum())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(csvData.getCommentNum())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(csvData.getLikeNum())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(csvData.getOccurrencePlace())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(csvData.getOccurrenceCity())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(csvData.getOccurrenceProvince())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(csvData.getOccurrenceCountry())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(csvData.getLon())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(csvData.getLat())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+name+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+CHECK+"\t\"\n";
                            str+=param;
                        }
                    }
                    bcpFileWriter.write(str.getBytes());
                    System.out.println("创建文件结束CSV");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("创建文件异常CSV");
                }try {
                    bcpFileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                //用户上报数据
                Map<String, Object> params = new HashMap<>();
                params.put("date1",date1);
                params.put("date2",date4);
                params.put("WeatherTypeId",a);
                Integer b = Integer.valueOf(req.getType());
                params.put("type",b);
                list2 = weatherMapper.findAllTypeByParams(params);

                File bcpFile = new File("/opt/project/file/export/"+req.getStarTime()+"/"+fileName+".csv"); //生成文件地址路径--相对路径
//                            File bcpFile = new File("D:\\AI+X project\\we-chat\\"+req.getStarTime()+"\\"+fileName+".csv"); //生成文件地址路径
                File parentFile = bcpFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                bcpFile.createNewFile();

                byte[] bom ={(byte) 0xEF,(byte) 0xBB,(byte) 0xBF};
                FileOutputStream bcpFileWriter = new FileOutputStream(bcpFile);
                System.out.println("创建文件开始CSV");
                try {
                    bcpFileWriter.write(bom);
                    // 写入文件头部
                    String title = "\"发布时间\",\"发生省份\",\"经度\",\"纬度\",\"天气类型\",\"描述\",\"冰雹直径大小\",\"图片视频地址\"";
                    bcpFileWriter.write((new String(title.getBytes(), "utf-8")).getBytes());
                    bcpFileWriter.write("\n".getBytes());
                    String str = "";
                    if(list2!=null && list2.size()>0){
                        String param = "";
                        for (int i = 0; i < list2.size(); i++) {
                            Weather weather = list2.get(i);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            String time = simpleDateFormat.format(weather.getOccurrenceTime());
                            Map<String, Object> params4 = new HashMap<>();
                            Map<String, Object> params3 = new HashMap<>();
                            params4.put("uuid",weather.getImagUuid());
                            List<FilePath> queryFilePaths1 = weatherMapper.queryFilePath(params4);
                            params3.put("uuid",weather.getVideoUuid());
                            List<FilePath> queryFilePaths2 = weatherMapper.queryFilePath(params3);
                            String paths="";
                            //http://124.70.45.54:8101/static/export/2023-10-16/nephogram_search.csv //例子
                            for (FilePath filePath : queryFilePaths1){
                                paths=paths+downloadImag+"/"+filePath.getPath()+",";
                            }
                            for (FilePath filePath : queryFilePaths2){
                                paths=paths+downloadVide+"/"+filePath.getPath()+",";
                            }

                            param = "\"\t"+time+"\","
                                    +"\"\t"+weather.getOccurrencePlace()+"\t\","
                                    +"\"\t"+weather.getOccurrencePlace1()+"\t\","
                                    +"\"\t"+weather.getOccurrencePlace2()+"\t\","
                                    +"\"\t"+weather.getWeatherTypeName()+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+weather.getDescribeName()+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+String.valueOf(weather.getHail())+"\t\"," // \t可将单元格设置为文本格式
                                    +"\"\t"+paths+"\t\"\n";
                            str+=param;
                        }
                    }
                    bcpFileWriter.write(str.getBytes());
                    System.out.println("创建文件结束CSV");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("创建文件异常CSV");
                }try {
                    bcpFileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            return SciaiHttpResponseEntityBuilder.builder().ok("导出成功！").build();

        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }
}